struct 模块可以把一个类型,如数字,转成固定长度的bytes类型

Format
(格式)
C Type
(c语言类型)
Python type
(Python类型)
Standard size
(bytes长度)
Notes
x
pad byte
no value


c
char
string of length 1
1

b
signed char
int
1
(3)
B
unsigned char
int
1
(3)
?
_Bool
bool
1
(1)
h
short
int
2
(3)
H
unsigned shoort
int
2
(3)
i
int
int
4
(3)
I
unsigned int
int
4
(3)
l
long
int
4
(3)
L
unsigned long
int
4
(3)
q
long long
int
8
(2),(3)
Q
unsigned long long
int
8
(2),(3)
f
float
float
4
(4)
d
double
float
8
(4)
s
char[]
str


p
char[]
str


P
void*
int

(5),(3)

import struct

num = 10
bytes_int = struct.pack('i', num)  # 将数字转化为固定长度的bytes类型 -> 'i' 是上面对照表的格式,代表 int
print(bytes_int)  # b'\n\x00\x00\x00'
print(len(bytes_int))  # 4
decoding_num = struct.unpack('i', bytes_int)  # 对固定长度的bytes类型进行解码
print(decoding_num)  # (10,)